<template>
  <el-dialog v-model="visible" title="字典列表">
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit">
          确定
        </el-button>
      </div>
    </template>
    <pure-table
      row-key="id"
      align-whole="center"
      :header-cell-style="{
        background: 'var(--el-fill-color-light)',
        color: 'var(--el-text-color-primary)'
      }"
      :data="tableData"
      :columns="columns"
      :max-height="500"
    >
      <template #append>
        <el-button plain class="w-full my-2" :icon="Plus" @click="onAdd">
          添加一行数据
        </el-button>
      </template>
      <template #operation="{ row, index }">
        <div class="btn-link">
          <el-link
            v-if="editMap[index]?.isEdit"
            type="primary"
            :underline="false"
            @click="onSave(row, index)"
            >保存</el-link
          >
          <el-link
            v-else
            type="primary"
            :underline="false"
            @click="onEdit(row, index)"
            >编辑</el-link
          >
          <el-link type="danger" :underline="false" @click="onDel(row, index)"
            >删除</el-link
          >
        </div>
      </template></pure-table
    >
  </el-dialog>
</template>

<script setup lang="tsx">
import { onMounted, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { dictApi, editDictApi } from "@/api/warehouse";
import { ElMessage } from "element-plus";
const visible = ref(false);

/* 数据处理 */
const editMap = ref({});
const tableData = ref([]);

const columns = [
  {
    label: "key",
    prop: "label",
    cellRenderer: ({ row, index }) => (
      <>
        {editMap.value[index]?.isEdit ? (
          <el-input v-model={row.label} clearable placeholder="请填写key" />
        ) : (
          <p>{row.label}</p>
        )}
      </>
    )
  },
  {
    label: "value",
    prop: "value",
    cellRenderer: ({ row, index }) => (
      <>
        {editMap.value[index]?.isEdit ? (
          <el-input v-model={row.value} clearable placeholder="请填写value" />
        ) : (
          <p>{row.value}</p>
        )}
      </>
    )
  },
  {
    label: "操作",
    fixed: "right",
    slot: "operation"
  }
];

const onAdd = () => {
  const item = { label: "", value: "", isEdit: true };
  tableData.value.push(item);
  editMap.value[tableData.value.length - 1] = Object.assign({ ...item });
};

const onDel = (row, index) => {
  tableData.value.splice(index, 1);
};

const onSave = (row, index) => {
  if (row.label && row.value) {
    editMap.value[index].isEdit = false;
  } else {
    ElMessage.error("请先填写key和value值");
  }
};

const onEdit = (row, index) => {
  editMap.value[index] = Object.assign({ ...row, isEdit: true });
};
const loading = ref(false);
const submit = () => {
  loading.value = true;
  const data = {} as any;
  tableData.value.map(item => {
    if (item.label && item.value) {
      data[item.label] = item.value;
    }
  });
  const params = {
    warehouseId: info.value?.warehouseId,
    jsonConfig: JSON.stringify(data),
    configId: info.value.configId
  };
  editDictApi(params)
    .then(res => {
      visible.value = false;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

const info = ref({} as any);
const show = (row = null) => {
  visible.value = true;
  tableData.value = [];
  editMap.value = {};
  if (row) {
    const { warehouseId } = row;
    dictApi({ warehouseId }).then(res => {
      info.value = { ...row, ...res.data };
      const jsonConfig = info.value?.jsonConfig ?? "{}";
      if (jsonConfig) {
        const tempObj = JSON.parse(jsonConfig.replace(/'/g, '"'));
        const list = [];
        for (const key in tempObj) {
          list.push({ label: key, value: tempObj[key] });
        }
        tableData.value = list;
      }
    });
  }
};
defineExpose({
  show
});
</script>
